﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace 文件上传及获取下载.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        string filePath = "SaveData";
        public FileController()
        {
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
        }
        [HttpPost]
        public IActionResult UploadFile(IFormFileCollection FormFiles, string DirName)
        {
            string saveDirPath = $"{filePath}\\{DirName}";
            if (!Directory.Exists(DirName))
            {
                Directory.CreateDirectory(saveDirPath);
            }
            foreach (var file in FormFiles)
            {
                try
                {
                    using (FileStream fsWrite = new FileStream($"{saveDirPath}\\{file.FileName}", FileMode.OpenOrCreate))
                    {
                        file.OpenReadStream().CopyTo(fsWrite);
                    }
                }
                catch (Exception ex)
                {
                    return BadRequest(new { state = 400, msg = ex.Message });
                }

            }
            return Ok(new { state = 200, msg = $"{FormFiles.Count}个文件上传成功" });
        }

        [HttpGet]
        public IActionResult GetFiles(string DirName)
        {
            string saveDirPath = $"{filePath}\\{DirName}";
            if (!Directory.Exists(saveDirPath))
            {
                return BadRequest(new { state = 400, msg = "获取失败" });
            }

            return Ok(new { state = 200, msg = Directory.GetFiles(saveDirPath).Select(x=>Path.GetFileName(x)) });
        }

        [HttpGet]
        public IActionResult GetDirName()
        {
            return Ok(new { state = 200, msg = Directory.GetDirectories(filePath).Select(x => Path.GetFileName(x)) });
        }
    }
}
